﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ExpertSystem.Exeptions;
using ExpertSystem.Interfaces;
using ExpertSystem.Views;

namespace ExpertSystem.Domains
{
    public class AsyncRuleset:Ruleset
    {
        public EventHandler Castomize;
        public event EventHandler RuleActive;
        public AsyncRuleset(string name):base(name,true)
        {
        }

        public override void ActivateRule(object o, EventArgs eventArgs)
        {
            RuleActive(o, eventArgs);
        }
        private void AsyncResolveVariable(IVariable variable, List<IRule> rules)
        {
            var en = rules.GetEnumerator();
            en.MoveNext();
            if (en.Current == null)
            {
                return;
            }
            while (!variable.HaveValue())
            {
                if (en.Current.CanBeAvtivated())
                {
                    if (en.Current.CanBeResolved())
                    {
                        en.Current.Resolve();
                        en.MoveNext();
                    }
                    else
                    {
                        if (!_stack.Contains(en.Current.CanNotBeResolvedVariable()))
                            _stack.Push(en.Current.CanNotBeResolvedVariable());
                        AsyncResolveVariable(en.Current.CanNotBeResolvedVariable(), _rules.Where(x => x.IsReternedValueEquals(en.Current.CanNotBeResolvedVariable()) && !x.IsActivated() && x.CanBeAvtivated()).ToList());
                        if (!_stack.Peek().HaveValue())
                        {
                            en.MoveNext();
                        }
                    }
                }
                else
                {
                    en.MoveNext();
                }

            }

        }

        public override void CastomizeView(object o, EventArgs eventArgs)
        {
            Castomize(o,eventArgs);
        }
        
        /*public void StartConsultation()
        {
            _stack.Push(_variables.First(x => x.IsGoal));
            while (!_variables.First(x => x.IsGoal).HaveValue())
            {
                if (!_rules.Any(x => x.IsReternedValueEquals(_stack.Peek())))
                {
                    throw new SystemCanNotBeResolved();
                }
                AsyncResolveVariable(_stack.Peek(), _rules.Where(x => x.IsReternedValueEquals(_stack.Peek()) && !x.IsActivated() && x.CanBeAvtivated()).ToList());
                if (_stack.Peek().HaveValue())
                {
                    _stack.Pop();
                }
            }
            MessageBox.Show(_variables.First(variable => variable.IsGoal).Value.ToString());
        }*/

     
    }
}
